package com.xsd.awen.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xsd.awen.config.WebResult;
import com.xsd.awen.domain.entity.App;
import com.xsd.awen.domain.entity.Project;
import com.xsd.awen.domain.po.ProjectPagePo;
import com.xsd.awen.domain.vo.ProjectVo;
import com.xsd.awen.mapper.AppMapper;
import com.xsd.awen.mapper.ProjectMapper;
import com.xsd.awen.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;

@Service
@Scope(proxyMode= ScopedProxyMode.TARGET_CLASS)
public class ProjectService {

    @Autowired
    ProjectMapper projectMapper;

    @Autowired
    AppMapper appMapper;

    public PageInfo<ProjectPagePo> page(ProjectVo projectVo){
        PageHelper.startPage(projectVo.getPage(),projectVo.getLimit());
        return new PageInfo<>(projectMapper.page(projectVo));
    }

    public String save(Project project){
        Integer count = projectMapper.countProject(project);
        if( count != null && count > 0 ){
            return WebResult.ERROR("用户名重复");
        }
        project.setId(UUIDUtils.generate());
        projectMapper.insert(project);
        return WebResult.OK();
    }

    public String update(Project project){
        Integer count = projectMapper.countUpdateProject(project);
        if( count != null && count > 0 ){
            return WebResult.ERROR("用户名重复");
        }
        projectMapper.updateById(project);
        return WebResult.OK();
    }

    public String delete(Project project){

        App app = new App();
        app.setProjectId(project.getId());
        Integer count = appMapper.countAppByProjectId(app);
        if( count != null && count > 0 ){
            return WebResult.ERROR("项目下有应用，不能删除");
        }else{
            projectMapper.deleteById(project);
            return WebResult.OK();
        }

    }

    public Project getById(String id){
        Project project = projectMapper.selectById(id);
        return project;
    }

}
